package IO.io_5_9;

import java.io.*;

/**
 * @author bruin_du
 * @description 复制文件夹
 * @date 2022/5/12 18:59
 **/
public class CopyDirectory {
    static String src = "C:\\Users\\乔治\\Desktop\\博客\\JavaWeb\\2022-05-08-Java19-22班-IO";
    static String dest = "C:\\Users\\乔治\\Desktop\\博客\\JavaWeb\\test";
    public static void main(String[] args) throws IOException {
        File srcFile = new File(src);
        if(!srcFile.exists()){
            System.out.println("想要复制的目录不存在");
            return;
        }
        File destFile = new File(dest);
        if(destFile.exists()){
            System.out.println("该目录已存在");
            return;
        }
        traversal(srcFile,destFile);

    }

    private static void traversal(File srcFile,File destFile) throws IOException {
        File[] files = srcFile.listFiles();
        if(files == null){
            return;
        }
        for (File file : files) {
            String subDirectory = file.getCanonicalPath().substring(src.length());
            String path = dest + subDirectory;
            File pathFile = new File(path);
            if(file.isDirectory()){
                pathFile.mkdirs();
            }else if(file.isFile()){
                copyFile(file,pathFile);
            }
            traversal(file,pathFile);
        }
    }

    private static void copyFile(File tmp,File pathFile) throws IOException {
        try(InputStream is = new FileInputStream(tmp)){
            try(OutputStream os = new FileOutputStream(pathFile)){
                byte[] buf = new byte[1024];
                while(true){
                    int n = is.read(buf);
                    if(n == -1)
                        break;
                    os.write(buf,0,n);
                }
                os.flush();
            }
        }
    }
}
